package annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 打印日志切面
 * </p>
 *
 * @author LovelyBigDuck
 * @date 2021/7/7 23:57
 */
@Component
@Aspect
public class ServiceLogAspect {
    public ThreadLocal<Long> local = new ThreadLocal<Long>();

    // 定义切入点，在自定义注解被调用的时候会执行该方法
    @Pointcut("@annotation(annotation.ServiceLog)")
    public void pointCut() {
        System.out.println("这里是切入点");
    }

    // 在切入点之前执行
    @Before("pointCut()")
    public void before(JoinPoint point) {
        String methodName = point.getTarget().getClass().getName()+"."+point.getSignature().getName();
        local.set(System.currentTimeMillis());
    }

    // 在切入点之后执行
    @After("pointCut()")
    public void after(JoinPoint point) {
        long start = local.get();
        String methodName = point.getTarget().getClass().getName()+"."+point.getSignature().getName();
        System.out.println("方法名："+methodName+" 总时长："+(System.currentTimeMillis()-start));
    }

    @AfterThrowing(pointcut="pointCut()",throwing="error")
    public void throwing(JoinPoint point,Throwable error) {
        System.out.println("error");
    }
}
